class MpdSyncWorker < BackgrounDRb::MetaWorker
  set_worker_name :mpd_sync_worker
  attr_accessor :progress
  
  def create(args = nil)
    self.progress = 0
    # this method is called, when worker is loaded for the first time
  end
  
  def progress
    return @progress.round
  end
  
  def sync
    processed_songs = []
    Jukebox.radio.update
    self.progress = 10
    
    songs = Jukebox.radio.songs
    
    songs.each do |song|
      s = Song.find_or_create_by_file song.file
      
      #Use the MPD::Song object data
      s.update_attributes song
      
      processed_songs << s.id
      @progress += (1.to_f / songs.length*90).to_f
      register_status(self.progress)
    end
    
    #Delete all songs remove from the mpd database
    Song.destroy_all ["id not in (?)", processed_songs]
    
    #Regenerate the Jukebox database (in case a song could not be loaded)
    MpdCallbacks.sync()
    
    logger.info "Sync with mpd complete (#{self.progress}%)"
    
  end
  
end

